from django.shortcuts import render

# Create your views here.
from django import http
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q

# from aijia.utils.qiniu_info import QI_NIU_IMAGES
from homes.models import House
from orders.models import Order

import json
from orders.models import Order
import datetime
from utils.response_code import RETCODE
# Create your views here.


# 评价订单
class CommentOrderView(LoginRequiredMixin,View):
    def put(self,request,order_id):
        # 接收参数
        json_dict=json.loads(request.body.decode())
        try:
            comment=json_dict.get('comment')
        except Exception as e:
            http.JsonResponse({'errno':RETCODE.REQERR,'errmsg':'订单评论信息不存在'})

        # 获取相关的订单信息
        try:
            order=Order.objects.get(id=order_id)
        except:
            return http.JsonResponse({'errno':RETCODE.DATAERR,'errmsg':'订单信息不存在'})

        # 添加评论
        order.comment=comment
        order.status=Order.ORDER_STATUS.get('COMPLETE')
        order.save()
        return http.JsonResponse({  "errno": RETCODE.OK,"errmsg": "评论成功"})


# 用户接单或者拒单
class HandleOrderView(LoginRequiredMixin,View):
    def put(self,request,order_id):
        # 接收参数
        json_dict=json.loads(request.body.decode())
        action=json_dict.get('action')
        reason=json_dict.get('reason',None)
        # 校验参数
        if None==Order.objects.get(id=order_id):
            return http.JsonResponse({'errno':RETCODE.DATAERR,'errmsg':'订单编号传入有误'})
        # 判断操作类型,进行相应操作
        if action=='accept':
            # 修改房屋信息中的订单数
            order=Order.objects.get(id=order_id)
            house=order.house
            house.order_count += 1
            house.room_count -=1
            order.status=Order.ORDER_STATUS.get('WAIT_COMMENT')
            order.save()
            house.save()
            response={
                "errno":RETCODE.OK,
                "errmsg": "操作成功"
            }
            #返回相应
            return http.JsonResponse(response)

        elif action=='reject':
            order = Order.objects.get(id=order_id)
            order.status=Order.ORDER_STATUS.get('REJECTED')
            order.comment=reason
            order.save()
            response={
                "errno": RETCODE.OK,
                "errmsg": "操作成功"
            }
            #返回相应
            return http.JsonResponse(response)


# 添加订单或者展示所有订单信息
class CreateOrderView(LoginRequiredMixin,View):
    def order_in(self,order):

        order_info = {
            "amount": order.amount,
            "comment": order.comment,
            "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "days": order.days,
            "end_date": order.end_date,
            "img_url": order.house.index_image_url,
            "order_id": order.id,
            "start_date": order.begin_date,
            "status": Order.ORDER_STATUS_ENUM[order.status],
            "title": order.house.title
        }
        return order_info

    def get(self,request):
        # 接收参数
        user=request.user
        role=request.GET.get('role')
        order_list = []

        # 获取订单,展示我租别人的房子
        if role=='custom':
            if None==user.orders.filter(user_id=user.id):
                order_list=[]
            else:
                orders=user.orders.filter(user_id=user.id).order_by('-create_time')
                for order in orders:
                    order_info=self.order_in(order)
                    order_list.append(order_info)

        elif role=='landlord':

            if None==user.houses:
                return http.JsonResponse({'data':None,'errmsg':'OK','你未发布过房源':'4002'})
            else:
                # 查询自己所有的房子
                houses=user.houses.all()
                for house in houses:
                    orders = house.order_set.all()
                    for order in orders:
                        order_info=self.order_in(order)
                        order_list.append(order_info)

        response={'data':{'orders':order_list},'errmsg':'OK','errno':RETCODE.OK}
        return http.JsonResponse(response)

    def post(self,request):
        # 接收参数
        user=request.user
        json_dict=json.loads(request.body.decode())
        # house_id = json_dict.get('house_id')
        house_id = 5
        start_date=json_dict.get('start_date')
        end_date=json_dict.get('end_date')

        # 校验参数是否齐全
        if not all([house_id,start_date,end_date]):
            return http.JsonResponse({'errno':RETCODE.PARAMERR,'errmsg':'缺少必传参数'})

        # 判断是否有对应的房屋
        try:
            House.objects.get(id=house_id)
        except House.DoesNotExist:
            return http.JsonResponse({'errno':RETCODE.DBERR,'errmsg':'不存在此房屋'})

        # 判断house_id是否为int类型
        try:
            house_id==int(house_id)
        except Exception:
            return http.JsonResponse({'errno':RETCODE.PARAMERR,'errmsg':'house_id数值错误'})

        # 校验用户是否为房东
        house=House.objects.get(id=house_id)
        if user.id==house.id:
            return http.JsonResponse({'errno':RETCODE.ROLEERR,'errmsg':'不能在自己房屋下单'})

        # 校验下单日期是否有效
        now_str=datetime.datetime.now().strftime('%Y-%m-%d')
        now_str=datetime.datetime.strptime(now_str,'%Y-%m-%d')
        start_date=datetime.datetime.strptime(start_date,'%Y-%m-%d')
        end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        if end_date<start_date:
            return http.JsonResponse({'errno':RETCODE.PARAMERR,'errmsg':'选择的下单时间有误'})
        elif start_date<now_str:
            return http.JsonResponse({'errno':RETCODE.PARAMERR,'errmsg':'不能选择过去时间下单'})
        days=(end_date-start_date).days
        house_price=house.price
        amount=days * house_price
        # 判断用户下单天数是否超出房东的规定
        # if days < house.min_days or days > house.max_days:
        #     return http.JsonResponse({'errno':RETCODE.PARAMERR,'errmsg':'下单时间超出房东规定'})
        # 获取剩余房间数目
        room_count=house.room_count
        # 房间数目大于0,直接下单
        if room_count>=1:
            try:
                order=Order.objects.create(
                    user_id=user.id,
                    house_id = house.id,
                    begin_date = start_date,
                    end_date = end_date,
                    days = days,
                    house_price =house_price ,
                    amount = amount,
                    status = Order.ORDER_STATUS.get('WAIT_ACCEPT'),
                    comment = ''
                )
                # 返回相应
                response={
                    "data": {
                        "order_id": order.id
                    },
                    "errno": RETCODE.OK,
                    "errmsg": "下单成功"
                }
                return http.JsonResponse(response)
            except Exception as e:
                print(e)
                return http.JsonResponse({'errno': RETCODE.IOERR, 'errmsg': '创建订单失败,请重试'})
        elif room_count==0:
            # 判断此时段内是否由其他用户预订房间
            orders=house.order_set.all()
            end_date=datetime.datetime.date(end_date)
            start_date = datetime.datetime.date(start_date)
            for order in orders:
                if (end_date < order.begin_date) or (start_date > order.end_date) :
                    try:
                        order = Order.objects.create(
                            user_id=user.id,
                            house_id=house.id,
                            begin_date=start_date,
                            end_date=end_date,
                            days=days,
                            house_price=house_price,
                            amount=amount,
                            comment=''
                        )
                        # 返回相应
                        response = {
                            "data": {
                                "order_id": order.id
                            },
                            "errno": RETCODE.OK,
                            "errmsg": "下单成功"
                        }
                        return http.JsonResponse(response)
                    except Exception as e:
                        print(e)
                        return http.JsonResponse({'errno': RETCODE.IOERR, 'errmsg': '创建订单失败,请重试'})
            else:
                return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '此时段房间已被预订完了'})

